package com.bing.utils;

import org.springframework.util.ResourceUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

/**
 * Created by Administrator on 2015/7/5.
 */
public final class ScriptUtils {

    static Invocable jsInvoke;

    static {
        ScriptEngineManager manager = new ScriptEngineManager();
//      ScriptEngine engine = manager.getEngineByExtension("js");
//      ScriptEngine engine = manager.getEngineByMimeType("text/javascript");
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        File file = null;
        try {
            file = ResourceUtils.getFile("classpath:com/bing/js/marked.min.js");
            engine.eval(new FileReader(file));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        }

        jsInvoke = (Invocable) engine;
    }

    /**
     * markdown 转化为html
     *
     * @param md
     * @return
     */
    public static String md2Html(String md) {
        String html = "";
        try {
            html = (String) jsInvoke.invokeFunction("marked", md);
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return html;
    }
}
